package GUI;

import util.User;
import util.UserDAO;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.image.BufferedImage;

/**
 * 找回密码界面
 */
public class ForgotPasswordFrame extends JFrame {
    private JTextField usernameField;
    private JTextField contactField;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;
    private JTextField verificationCodeField;
    private JButton resetButton;
    private JButton backButton;
    private JLabel messageLabel;
    private JLabel captchaLabel;

    private LoginFrame loginFrame;
    private String captchaText;

    public ForgotPasswordFrame(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;

        // 设置窗口标题和大小
        setTitle("绿色出行系统 - 找回密码");
        setSize(500, 550);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中显示
        setResizable(false);

        // 设置自定义内容面板（带渐变背景）
        setContentPane(new GradientPanel());
        getContentPane().setLayout(new BorderLayout());

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);
        titlePanel.setBorder(new EmptyBorder(20, 0, 10, 0));

        JLabel titleLabel = new JLabel("找回密码", JLabel.CENTER);
        titleLabel.setFont(new Font("等线", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 100, 0));
        titlePanel.add(titleLabel, BorderLayout.CENTER);

        getContentPane().add(titlePanel, BorderLayout.NORTH);

        // 创建找回密码面板
        JPanel forgotPanel = new JPanel();
        forgotPanel.setLayout(new GridBagLayout());
        forgotPanel.setOpaque(false);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(10, 15, 10, 15);

        // 添加用户名字段
        addFormField(forgotPanel, constraints, "用户名:", usernameField = new RoundedTextField(20), 0);

        // 添加联系方式字段
        addFormField(forgotPanel, constraints, "联系方式:", contactField = new RoundedTextField(20), 1);

        // 添加验证码字段和发送按钮
        JLabel codeLabel = new JLabel("验证码:");
        codeLabel.setFont(new Font("等线", Font.BOLD, 14));
        codeLabel.setForeground(new Color(50, 50, 50));
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        forgotPanel.add(codeLabel, constraints);

        JPanel codePanel = new JPanel(new BorderLayout(10, 0));
        codePanel.setOpaque(false);

        verificationCodeField = new RoundedTextField(8);
        verificationCodeField.setFont(new Font("等线", Font.PLAIN, 14));
        codePanel.add(verificationCodeField, BorderLayout.WEST);

        // 创建图形验证码标签
        captchaLabel = new JLabel();
        captchaLabel.setPreferredSize(new Dimension(120, 35));
        captchaLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
        captchaLabel.setToolTipText("点击刷新验证码");
        captchaLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                refreshCaptcha();
            }
        });
        codePanel.add(captchaLabel, BorderLayout.EAST);

        constraints.gridx = 1;
        constraints.gridy = 2;
        constraints.anchor = GridBagConstraints.WEST;
        forgotPanel.add(codePanel, constraints);

        // 生成初始验证码
        refreshCaptcha();

        // 移除计时器标签相关代码
        constraints.gridx = 1;
        constraints.gridy = 3;
        constraints.anchor = GridBagConstraints.WEST;
        JLabel captchaHintLabel = new JLabel("点击图片可刷新验证码");
        captchaHintLabel.setFont(new Font("等线", Font.PLAIN, 12));
        captchaHintLabel.setForeground(new Color(100, 100, 100));
        forgotPanel.add(captchaHintLabel, constraints);

        // 添加新密码字段
        addFormField(forgotPanel, constraints, "新密码:", newPasswordField = new RoundedPasswordField(20), 4);

        // 添加确认密码字段
        addFormField(forgotPanel, constraints, "确认新密码:", confirmPasswordField = new RoundedPasswordField(20), 5);

        // 添加密码规则提示
        JLabel passwordRuleLabel = new JLabel("<html><small>密码要求：包含大小写字母、数字，长度至少8位</small></html>");
        passwordRuleLabel.setFont(new Font("等线", Font.ITALIC, 12));
        passwordRuleLabel.setForeground(new Color(100, 100, 100));
        constraints.gridx = 1;
        constraints.gridy = 6;
        constraints.anchor = GridBagConstraints.WEST;
        forgotPanel.add(passwordRuleLabel, constraints);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setOpaque(false);

        // 创建重置密码按钮
        resetButton = new RoundedButton("重置密码");
        resetButton.setFont(new Font("等线", Font.BOLD, 14));
        resetButton.setPreferredSize(new Dimension(120, 40));
        resetButton.addActionListener(e -> resetPassword());
        buttonPanel.add(resetButton);

        // 创建返回按钮
        backButton = new RoundedButton("返回登录");
        backButton.setFont(new Font("等线", Font.BOLD, 14));
        backButton.setPreferredSize(new Dimension(120, 40));
        backButton.addActionListener(e -> backToLogin());
        buttonPanel.add(backButton);

        constraints.gridx = 0;
        constraints.gridy = 7;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        forgotPanel.add(buttonPanel, constraints);

        // 创建消息标签
        messageLabel = new JLabel("", JLabel.CENTER);
        messageLabel.setFont(new Font("等线", Font.PLAIN, 12));
        messageLabel.setForeground(Color.RED);
        constraints.gridx = 0;
        constraints.gridy = 8;
        constraints.gridwidth = 2;
        forgotPanel.add(messageLabel, constraints);

        // 添加面板到内容面板
        JScrollPane scrollPane = new JScrollPane(forgotPanel);
        scrollPane.setBorder(null);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 添加底部版权信息
        JLabel copyrightLabel = new JLabel("© 2025 绿色出行系统 版权所有", JLabel.CENTER);
        copyrightLabel.setFont(new Font("等线", Font.PLAIN, 10));
        copyrightLabel.setForeground(new Color(100, 100, 100));
        copyrightLabel.setBorder(new EmptyBorder(10, 0, 10, 0));
        getContentPane().add(copyrightLabel, BorderLayout.SOUTH);
    }

    /**
     * 添加表单字段
     */
    private void addFormField(JPanel panel, GridBagConstraints constraints, String labelText, JComponent field,
            int row) {
        JLabel label = new JLabel(labelText);
        label.setFont(new Font("等线", Font.BOLD, 14));
        label.setForeground(new Color(50, 50, 50));
        constraints.gridx = 0;
        constraints.gridy = row;
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        panel.add(label, constraints);

        if (field instanceof JTextField) {
            ((JTextField) field).setFont(new Font("等线", Font.PLAIN, 14));
        }
        constraints.gridx = 1;
        constraints.gridy = row;
        constraints.anchor = GridBagConstraints.WEST;
        panel.add(field, constraints);
    }

    /**
     * 生成图形验证码
     */
    private void refreshCaptcha() {
        // 生成随机验证码文本
        captchaText = generateRandomCode();

        // 创建图形验证码
        captchaLabel.setIcon(new ImageIcon(createCaptchaImage(captchaText)));
    }

    /**
     * 创建验证码图片
     */
    private Image createCaptchaImage(String text) {
        // 创建图片
        int width = 120;
        int height = 35;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // 设置背景
        g2d.setColor(new Color(240, 240, 250));
        g2d.fillRect(0, 0, width, height);

        // 绘制干扰线
        g2d.setColor(new Color(200, 200, 200));
        Random rand = new Random();
        for (int i = 0; i < 8; i++) {
            int x1 = rand.nextInt(width);
            int y1 = rand.nextInt(height);
            int x2 = rand.nextInt(width);
            int y2 = rand.nextInt(height);
            g2d.drawLine(x1, y1, x2, y2);
        }

        // 绘制干扰圆点
        for (int i = 0; i < 20; i++) {
            int x = rand.nextInt(width);
            int y = rand.nextInt(height);
            g2d.setColor(new Color(rand.nextInt(100) + 150, rand.nextInt(100) + 150, rand.nextInt(100) + 150));
            g2d.fillOval(x, y, 4, 4);
        }

        // 绘制验证码文本
        g2d.setFont(new Font("Arial", Font.BOLD, 24));
        FontMetrics metrics = g2d.getFontMetrics();
        int x = (width - metrics.stringWidth(text)) / 2;
        int y = (height - metrics.getHeight()) / 2 + metrics.getAscent();

        // 文字有不同的颜色和旋转角度
        for (int i = 0; i < text.length(); i++) {
            g2d.setColor(new Color(rand.nextInt(80), rand.nextInt(80), rand.nextInt(80) + 100));
            // 获取每个字符的旋转角度(-15到15度)
            double angle = (rand.nextDouble() - 0.5) * Math.PI / 6;
            g2d.rotate(angle, x + metrics.charWidth(text.charAt(i)) / 2, y);
            g2d.drawString(text.substring(i, i + 1), x, y);
            g2d.rotate(-angle, x + metrics.charWidth(text.charAt(i)) / 2, y);
            x += metrics.charWidth(text.charAt(i));
        }

        g2d.dispose();
        return image;
    }

    /**
     * 重置密码
     */
    private void resetPassword() {
        String username = usernameField.getText().trim();
        String contact = contactField.getText().trim();
        String verificationCode = verificationCodeField.getText().trim();
        String newPassword = new String(newPasswordField.getPassword());
        String confirmPassword = new String(confirmPasswordField.getPassword());

        // 验证所有字段
        if (username.isEmpty() || contact.isEmpty() || verificationCode.isEmpty() ||
                newPassword.isEmpty() || confirmPassword.isEmpty()) {
            showErrorMessage("所有字段都必须填写！");
            return;
        }

        // 验证验证码 (不区分大小写)
        if (captchaText == null || !captchaText.equalsIgnoreCase(verificationCode)) {
            showErrorMessage("验证码不正确！");
            refreshCaptcha(); // 刷新验证码
            return;
        }

        // 检查密码强度
        if (newPassword.length() < 8 || !newPassword.matches(".*[A-Z].*") ||
                !newPassword.matches(".*[a-z].*") || !newPassword.matches(".*[0-9].*")) {
            showErrorMessage("密码必须至少包含8个字符，且包含大小写字母和数字！");
            return;
        }

        // 检查两次输入的密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            showErrorMessage("两次输入的密码不一致！");
            return;
        }

        // 重置密码
        UserDAO userDAO = new UserDAO();
        boolean success = userDAO.resetPassword(username, contact, newPassword);

        if (success) {
            JOptionPane.showMessageDialog(this,
                    "密码重置成功！请使用新密码登录。",
                    "重置成功",
                    JOptionPane.INFORMATION_MESSAGE);
            backToLogin();
        } else {
            showErrorMessage("密码重置失败，请稍后再试！");
        }
    }

    /**
     * 生成随机验证码
     */
    private String generateRandomCode() {
        Random random = new Random();
        // 生成4位验证码，包含数字和大写字母
        StringBuilder sb = new StringBuilder();
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // 排除容易混淆的字符 O, 0, 1, I
        for (int i = 0; i < 4; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 显示错误信息
     */
    private void showErrorMessage(String message) {
        messageLabel.setText(message);
        messageLabel.setForeground(Color.RED);
        // 使用计时器让消息在5秒后消失
        Timer timer = new Timer(5000, e -> messageLabel.setText(""));
        timer.setRepeats(false);
        timer.start();
    }

    /**
     * 显示成功信息
     */
    private void showSuccessMessage(String message) {
        messageLabel.setText(message);
        messageLabel.setForeground(new Color(0, 128, 0));
        // 使用计时器让消息在5秒后消失
        Timer timer = new Timer(5000, e -> messageLabel.setText(""));
        timer.setRepeats(false);
        timer.start();
    }

    /**
     * 返回登录界面
     */
    private void backToLogin() {
        loginFrame.setVisible(true);
        dispose();
    }

    /**
     * 渐变背景面板
     */
    private class GradientPanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            int w = getWidth();
            int h = getHeight();

            // 创建渐变颜色
            GradientPaint gradient = new GradientPaint(0, 0, new Color(220, 240, 240),
                    0, h, new Color(180, 210, 210));
            g2d.setPaint(gradient);
            g2d.fillRect(0, 0, w, h);

            // 添加一些装饰性元素
            g2d.setColor(new Color(0, 90, 90, 20));
            for (int i = 0; i < 5; i++) {
                int size = 50 + i * 20;
                g2d.fillOval(w - size - 20, h - size - 20, size, size);
            }

            // 左上角装饰
            g2d.setColor(new Color(0, 90, 90, 15));
            for (int i = 0; i < 3; i++) {
                int size = 30 + i * 15;
                g2d.fillOval(20, 20, size, size);
            }
        }
    }

    /**
     * 圆角文本框
     */
    private class RoundedTextField extends JTextField {
        public RoundedTextField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 圆角密码框
     */
    private class RoundedPasswordField extends JPasswordField {
        public RoundedPasswordField(int columns) {
            super(columns);
            setOpaque(false);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(180, 180, 180)),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(new Color(255, 255, 255, 220));
            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
            super.paintComponent(g);
            g2.dispose();
        }
    }

    /**
     * 圆角按钮
     */
    private class RoundedButton extends JButton {
        public RoundedButton(String text) {
            super(text);
            setOpaque(false);
            setFocusPainted(false);
            setBorderPainted(false);
            setContentAreaFilled(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            if (getModel().isPressed()) {
                g2.setColor(new Color(0, 80, 80));
            } else if (getModel().isRollover()) {
                g2.setColor(new Color(0, 110, 110));
            } else {
                g2.setColor(new Color(0, 130, 130));
            }

            g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);

            g2.setColor(Color.WHITE);
            g2.setFont(getFont());
            FontMetrics fm = g2.getFontMetrics();
            int x = (getWidth() - fm.stringWidth(getText())) / 2;
            int y = (getHeight() - fm.getHeight()) / 2 + fm.getAscent();
            g2.drawString(getText(), x, y);
            g2.dispose();
        }
    }
}